package com.jt.provider.controller;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@RestController
@RefreshScope
@Slf4j   //自动创建日志log对象
public class ProviderCacheController {
//    private static Logger log =
//            LoggerFactory.getLogger(ProviderLogController.class);
    /**
     * 从配置文件读取配置赋值给属性
     * */
    @Value(value = "${useLocalCache:false}")
    private boolean useLocalCache;

    @GetMapping("/provider/cache01")
    public String doUseLocalCache01(){
        return String.format("useLocalCache value is %s",useLocalCache);
    }
    //定义一个本地cache（缓存）
    private CopyOnWriteArrayList<String> cache = new CopyOnWriteArrayList<>();
    @GetMapping("/provider/cache02")
    public List<String> doUseLocalCache02(){
        if(!useLocalCache){
            log.info("select data from database");
            return Arrays.asList("A","B","C");
        }
        if(cache.isEmpty()){
            synchronized (this){  //双重校验
        if(cache.isEmpty()) {
            //模拟从数据库获取数据
            List<String> data = Arrays.asList("A", "B", "C");
            //将数据放入cache中
            cache.addAll(data);
        }
        }
        }
        System.out.println(useLocalCache);
        log.info("select data from cache");
        return cache;
    }
}
